# -*- encoding: utf-8 -*-

"""
@File:      tc_readline_fun_006.py
@Time:      2024-03-04 10:30:00
@Author:    qintingting
@Version:   1.0
@Contact:   wb-qtt862918@alibaba-inc.com
@License:   Mulan PSL v2
@Modify:    qintingting
"""
import pexpect
from common.basetest import LocalTest

class Test(LocalTest):
    """
    See tc_readline_fun_006.yaml for details

    :avocado: tags=P2,noarch,local,fixed
    """
    PARAM_DIC = {"pkg_name": "readline readline-devel"}
    def setUp(self):
        super().setUp(self.PARAM_DIC)
        cmdline='''cat > readline_fun_006.c <<EOF
#include <stdio.h>
#include <stdlib.h> 
#include <readline/readline.h>
#include <readline/history.h>

// 函数原型声明
int my_rl_function(int, int);

int main() {
    // 初始化 readline 的历史记录功能
    using_history();

    // 将 'q' 键绑定到 my_rl_function
    rl_bind_key('q', my_rl_function);

    // 读取输入直到用户退出程序
    char *input = NULL;
    while (1) {
        input = readline("Input: ");

        // 检查输入是否为空或者用户输入了 'exit'
        if (!input || strcmp(input, "exit") == 0) {
            break;
        }

        // 输出用户输入的内容
        printf("You entered: %s\\n", input);

        // 将输入添加到历史记录
        add_history(input);

        // 释放为输入分配的内存
        free(input);
    }

    // 清理 readline 使用的内存
    clear_history();

    printf("Exiting program.\\n");
    return 0;
}

// 自定义的键绑定处理函数
int my_rl_function(int count, int key) {
    printf("Custom key binding triggered!\\n");

    // 刷新输出，以免 readline 的输出干扰我们的打印
    rl_on_new_line();
    
    // 通知 readline 我们已经处理了按键事件
    return 0;
}
EOF
'''
        self.cmd(cmdline)

    def test(self):
        self.cmd("gcc -o readline_fun_006 readline_fun_006.c -lreadline")
        code, result = self.cmd("file readline_fun_006")
        self.assertIn("executable", result)
        child = pexpect.spawnu('./readline_fun_006', timeout=2)
        child.expect('Input:')
        try:
            child.send('q')
            child.expect('Custom key binding triggered!')
            child.expect('Input:')
            print("Successfully triggered custom key binding function detected")
        except pexpect.exceptions.TIMEOUT as e:
            print("Failed to detect the custom key binding function's output.")
            print("Specific error:", e)
        
        child.sendline('exit')
        child.expect(pexpect.EOF)
        child.close()
        
        # confirm exit status
        if child.exitstatus == 0:
            print('Program exited successfully.')
        else:
            print('Program did not exit successfully.')
    def tearDown(self):
        super().tearDown(self.PARAM_DIC)
        self.cmd("rm -rf readline_fun_006 readline_fun_006.c")